package org.itboys.core.service.mysql.front;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.common.WalletRecordEnum;
import org.itboys.core.dao.wallet.SundayWalletMapper;
import org.itboys.core.dao.wallet.SundayWalletRecordMapper;
import org.itboys.core.entity.mysql.wallet.SundayWallet;
import org.itboys.core.entity.mysql.wallet.SundayWalletExample;
import org.itboys.core.entity.mysql.wallet.record.SundayWalletRecord;
import org.itboys.core.entity.mysql.wallet.record.SundayWalletRecordExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author：贾琦磊
 * @Date：2018/12/24
 * @Description：钱包记录service
 */
@Service
public class SundayFrontWalletRecordService {

    @Autowired
    private SundayWalletRecordMapper walletRecordMapper;
    @Autowired
    private SundayWalletMapper walletMapper;

    /**
     * 创建钱包变更记录，默认为未生效，需要改变钱包数据的调用生效方法
     *
     * @param memberId   用户id
     * @param money      钱数
     * @param operation  针对于钱包金额的运算方式 1：加法，-1：减法
     * @param recordEnum 记录类型枚举，查看WalletRecordEnum
     * @param remark 订单号
     * @return 生成记录的id
     */
    public Long createWalletRecord(Long memberId, BigDecimal money, Integer operation, WalletRecordEnum recordEnum,String remark) {
        SundayWalletExample example = new SundayWalletExample();
        example.createCriteria().andIsDeletedEqualTo(SundayCommonConstants.NO)
                .andMemberIdEqualTo(memberId);
        List<SundayWallet> wallets = walletMapper.selectByExample(example);
        Long walletId;
        if (!ListUtil.isNotNull(wallets)) {
            //没有钱包的将会新建一个钱包
            SundayWallet wallet = new SundayWallet(memberId, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
            walletMapper.insert(wallet);
            walletId = wallet.getId();
        } else {
            walletId = wallets.get(0).getId();
        }
        SundayWalletRecord walletRecord = new SundayWalletRecord();
        walletRecord.setMemberId(memberId);
        walletRecord.setWalletId(walletId);
        walletRecord.setMoney(money);
        walletRecord.setStatus(SundayCommonConstants.NO);
        walletRecord.setType(recordEnum.getCode());
        walletRecord.setRemark(recordEnum.getDesc());
        walletRecord.setOperation(operation);
        walletRecord.setRemark(remark);
        walletRecordMapper.insert(walletRecord);
        return walletRecord.getId();
    }

    /**
     * 执行钱包记录
     *
     * @param walletRecordId 记录id
     */
    @Transactional(rollbackFor = Exception.class)
    public void executeWalletRecord(Long walletRecordId) {
        //查出未生效的记录
        SundayWalletRecordExample example = new SundayWalletRecordExample();
        example.createCriteria().andIsDeletedEqualTo(SundayCommonConstants.NO)
                .andStatusEqualTo(SundayCommonConstants.NO)
                .andIdEqualTo(walletRecordId);
        List<SundayWalletRecord> walletRecords = walletRecordMapper.selectByExample(example);
        if (!ListUtil.isNotNull(walletRecords))
            throw new ErrorException(ExceptionEnum.GET_WALLET_RECORD_EXCEPTION.getValue());
        SundayWalletRecord record = walletRecords.get(0);
        SundayWallet wallet = walletMapper.selectByPrimaryKey(record.getWalletId());
        if (wallet == null) throw new ErrorException(ExceptionEnum.GET_WALLET_RECORD_EXCEPTION.getValue());
        //更新钱包
        BigDecimal recordMoney = record.getMoney();
        BigDecimal walletMoney = wallet.getMoney();
        BigDecimal walletSum = wallet.getSum();
        BigDecimal walletExtract = wallet.getExtract();
        //目标钱包入账
        if (record.getOperation().equals(SundayCommonConstants.WALLET_RECORD_OPERATION_ADD)) {
            //钱包剩余钱数和总入账更新
            walletMoney = walletMoney.add(recordMoney);
            walletSum = walletSum.add(recordMoney);
        } else if (record.getOperation().equals(SundayCommonConstants.WALLET_RECORD_OPERATION_SUBTRACT)) {
            walletMoney = walletMoney.subtract(recordMoney);
        }
        if (record.getType().equals(WalletRecordEnum.TIXIAN.getCode())) {
            //如果为提现，需要将钱包的提现金额增加
            walletExtract.add(recordMoney);
        }
        wallet.setSum(walletSum);
        wallet.setMoney(walletMoney);
        wallet.setExtract(walletExtract);
        walletMapper.update(wallet);
        record.setStatus(SundayCommonConstants.YES);
        //将该条记录设置为已生效
        walletRecordMapper.update(record);
    }

    public void updateStatus(Long id,Integer state){
        SundayWalletRecord walletRecord = walletRecordMapper.selectByPrimaryKey(id);
        walletRecord.setStatus(state);
        walletRecordMapper.update(walletRecord);
        //如果驳回提现申请,将用户钱包的钱返还给用户余额并且减掉已提现金额
        if(SundayCommonConstants.TX_APPLY_STATE_REJECT.equals(state)){
            Long walletId=walletRecord.getWalletId();
            //生成一条驳回记录
            SundayWalletRecord rejectRecord=new SundayWalletRecord(walletRecord.getMemberId(),walletId,walletRecord.getMoney(),
                    SundayCommonConstants.WALLET_RECORD_OPERATION_ADD
                    ,WalletRecordEnum.TXBOHUI.getCode(),"已返现",SundayCommonConstants.TX_APPLY_STATE_REJECT);
            walletRecordMapper.insert(rejectRecord);
            //改变用户钱包的金额
            SundayWallet wallet = walletMapper.selectByPrimaryKey(walletId);
            wallet.setMoney(wallet.getMoney().add(walletRecord.getMoney()));
            wallet.setExtract(wallet.getExtract().subtract(walletRecord.getMoney()));
            walletMapper.update(wallet);
        }
    }
}
